package com.ms.code.generate;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

import java.io.StringWriter;

/**
 * <b>description</b>：freemarker工具类 <br>
 * <b>time</b>：2014-12-18上午10:37:09 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class FreemarkerUtil {

    private static Configuration cfg = null;

    public static Configuration getCfg() throws TemplateException {
        if (cfg == null) {
            synchronized (FreemarkerUtil.class) {
                if (cfg == null) {
                    cfg = new Configuration();
                    cfg.setDefaultEncoding("UTF-8");
                    cfg.setClassicCompatible(true);
                    cfg.setTemplateUpdateDelay(10);
                    // 设置模板文件所在的目录
                    cfg.setClassForTemplateLoading(FreemarkerUtil.class,
                            "/ftl/");
                }
            }
        }
        return cfg;
    }

    /**
     * 根据freemarker文件获取内容
     *
     * @param ftlFileName
     * @param rootMap
     * @return
     * @throws Exception
     */
    public static String getFtlToString(String ftlFileName, Object rootMap)
            throws Exception {
        StringWriter sw = new StringWriter();
        getCfg().getTemplate(ftlFileName + ".ftl").process(rootMap, sw);
        return sw.toString();
    }

}
